﻿// MIT License (MIT)
// 
// Copyright (c) 2014 K Ercan Turkarslan
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// 

using System;
using System.Collections.Generic;
using System.Linq;

namespace Mios.MiosConnection
{
    public sealed class Ui5Controllers
    {
        public String Username { get; private set; }
        public String Password { get; private set; }

        #region Public ReadOnly Controllers : Array of Ui5Controller;

        private readonly List<Ui5Controller> _controllers;

        public Ui5Controller[] Controllers
        {
            get { return _controllers.ToArray(); }
        }

        #endregion

        #region ParseListOfControllers method

        /// https://sta1.mios.com/locator.php?username=thisuser
        ///  
        /// 30001234,10.0.1.12,thisuser,fwd5.mios.com,fwd6.mios.com
        /// 35004321,10.0.1.10,otheruser,fwd5.mios.com,fwd6.mios.com
        /// 35006110,,thisuser,fwd5.mios.com,fwd6.mios.com
        ///  
        /// 1. A controller in this local network and belongs to thisuser.
        /// 2. A controller in this local network but belongs to otheruser. thisuser is not a registered user of it.
        /// 3. A controller which is not in your local network but belongs to thisuser. thisuser can access it with remote connection.
        private void ParseListOfControllers(string httpString, Boolean filterWithUsername)
        {
            foreach (var miosSystem in httpString.Split('\n'))
            {
                if (String.IsNullOrEmpty(miosSystem.Trim())) 
                    continue;

                var sysProperties = miosSystem.Split(',');
                if (sysProperties.Length < 5)
                    continue;

                if (filterWithUsername && (sysProperties[2] != Username)) 
                    continue;

                var newController = new Ui5Controller(sysProperties[0], // ID
                                                      sysProperties[1], // IPAddress
                                                      sysProperties[2], // Username
                                                      (sysProperties[2] == Username) ? Password : null, 
                                                      sysProperties[3], // Forward Server 1
                                                      sysProperties[4] // Forward Server 2
                    );
                _controllers.Add(newController);
            }
        }

        #endregion

        #region Contructor(s)

        public Ui5Controllers(String username = null, String password = null, Boolean filterWithUsername = false)
        {
            _controllers = new List<Ui5Controller>();

            Username = String.IsNullOrEmpty(username) ? null : username;
            Password = String.IsNullOrEmpty(Username) ? null : password;

            var usernameString = String.IsNullOrEmpty(Username) ? String.Empty : String.Format("?username={0}", username);

            var listOfControllers =
                HttpConnection.HttpGetString(String.Format("https://sta1.mios.com/locator.php{0}", usernameString));

            ParseListOfControllers(listOfControllers, Username != null && filterWithUsername);
        }

        #endregion

        public Ui5Controller GetController(String engineSerial)
        {
            return _controllers.FirstOrDefault(controller => controller.EngineSerial == engineSerial);
        }
    }
}